package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"video-sys/models"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	userId, _ := strconv.Atoi(c.PostForm("user_id"))

	if title == "" || content == "" || img == "" || userId == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}

	movies := models.Movies{
		Title:     title,
		Content:   content,
		Img:       img,
		UserID:    userId,
		LikeCount: 0,
		GunCount:  0,
	}
	err := models.DB.Create(&movies).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片加载失败",
		})
		return
	}
	if file.Size > 2*1024*1024 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片大小不能超过2M",
		})
		return
	}
	path := "static/img/" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	url := "http://" + c.Request.Host + "/" + path
	c.JSON(200, gin.H{
		"msg":  "发布成功",
		"data": url,
	})
	return
}
func LikeList(c *gin.Context) {
	var movies []models.Movies
	err := models.DB.Order("like_count desc").Find(&movies).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": movies,
	})
	return
}
func GunList(c *gin.Context) {
	var movies []models.Movies
	err := models.DB.Order("gun_count desc").Find(&movies).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": movies,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.Movies{}).Count(&count)

	var movies []models.Movies
	err := models.DB.Offset(offset).Limit(size).Find(&movies).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": movies,
	})
	return
}
